package bill_management

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"tao-admin/internal/model"
	"tao-admin/utils"
)

type BillService struct {
	BillManager *BillManager
}

func NewBillService() *BillService {
	return &BillService{
		BillManager: &BillManager{},
	}
}

func (s *BillService) CreateBillItem(ctx *gin.Context) (err error, msg string) {
	var item model.BillTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}

	if item.Type == nil || item.Value == nil || item.Tags == nil ||
		item.Date == nil {
		return nil, "存在必填项未填写！"
	}
	now := utils.GetCurrentTimeStamp()
	item.Ctime = utils.Convert(now)
	item.Mtime = utils.Convert(now)

	err = s.BillManager.CreateBillMng(ctx, item)
	if err != nil {
		return err, "插入数据出错！"
	}
	return nil, ""
}

func (s *BillService) UpdateBillItem(ctx *gin.Context) (err error, msg string) {
	var item model.BillTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！(Unmarshal)"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}

	now := utils.GetCurrentTimeStamp()
	item.Mtime = utils.Convert(now)
	err = s.BillManager.UpdateBillMng(ctx, item)
	if err != nil {
		return err, "更新数据出错！"
	}
	return nil, ""
}

func (s *BillService) DeleteBillItem(ctx *gin.Context) (err error, msg string) {
	var item model.BillTab
	bodyBytes, err := ioutil.ReadAll(ctx.Request.Body)
	if err != nil {
		return err, "数据解析出错！(Read Request.Body)"
	}
	err = json.Unmarshal(bodyBytes, &item)
	if err != nil {
		return err, "数据解析出错！"
	}
	if item.Id == nil {
		return nil, "Id必传！"
	}
	err = s.BillManager.DeleteBillMng(ctx, item)
	if err != nil {
		return err, "删除数据出错！"
	}
	return nil, ""
}

func (s *BillService) GetBillInfos(ctx *gin.Context) ([]model.BillTab, int64, error) {
	condition := &SearchBillCondition{}
	v, e := ctx.Get("type")
	if e {
		v2 := v.(int64)
		condition.Type = &v2
	}

	if value1, isExist := ctx.Get("value"); isExist == true {
		value2 := value1.(int64)
		condition.Value = &value2
	}

	if tags, isExist := ctx.GetQuery("tags"); isExist == true {
		condition.Tags = &tags
	}

	list, total, err := s.BillManager.SearchBillByConditionMng(ctx, condition)
	if err != nil {
		return nil, 0, err
	}
	log.Printf("SearchByConditionMng, list: %v, total: %v", &list, total)
	return list, total, nil
}
